<template>
  <div>
    <el-button @click="testb">test button</el-button>
    <el-tabs v-model="activeTab" type="card" @tab-remove="removeTab" @tab-click="tabClick">
      <el-tab-pane v-for="(item, index) in tabsItem"
                   :key="item.chat_id"
                   :label="item.title"
                   :name="item.chat_id"
                   :ref="item.ref">
        <component :is="item.content"
                   v-bind:chat_id='item.chat_id'
                   v-bind:chat_data="chat_data"
                   v-bind:c_name="item.title"
                   @sendMes="sendMes">

        </component>
      </el-tab-pane>
    </el-tabs>
  </div>
</template>

<script>
import ChatRoom from "@/components/ChatRoom";
import axios from "axios";
import SockJS from 'sockjs-client';
import Stomp from 'stompjs';

export default {
  name: "Home",
  data() {
    return {
      stompClient: null,
      isCollapse: false,  //false为展开 true为收缩
      socket: null,
      activeTab: '1', //默认显示的tab
      tabIndex: 2, //tab目前显示数
      chat_data: [
        {
          uid: 1,
          name: 'test',
          chat_id: 1,
          content: "testceauicbiaeviaeiaeiviabciyvyarvbkarvbjarkygfxbu" +
              "agxyabgrfubygrfuxynrfugrn3yxuwyguifngunfyxgfnuguzgnu3guzg" +
              "nfi3gfiug3wfnwerunfywerfgnweuirngfurngfuxwgfuwi",
          time: this.getTime(),
        },
      ],
      tabsItem: [
        {
          title: '首页',
          chat_id: 0,
          closable: false,
          ref: 'tabs',
          content: ChatRoom
        },
        {
          title: '测试对话1',
          chat_id: 1,
          closable: true,
          ref: 'tabs',
          content: ChatRoom
        }
      ],
      tabsPath: [
        {
          chat_id: 0,
          path: '/chatroom',
          path_name: 'chatroom'
        },
        {
          chat_id: 1,
          path: '/chatroom',
          path_name: 'chatroom'
        }
      ]
    }
  },
  computed: {
    setHeight() {
      return document.documentElement.clientHeight - 65
    }
  },
  watch: {
    '$route'(to, from) {
      this.$router.go(0);
    }
  },
  methods: {
    testb() {
      this.chat_data.push();
    },
    getTime() {
      //获取当前时间并打印
      let yy = new Date().getFullYear();
      let mm = new Date().getMonth() + 1;
      let dd = new Date().getDate();
      let hh = new Date().getHours();
      let mf = new Date().getMinutes() < 10 ? '0' + new Date().getMinutes() : new Date().getMinutes();
      let ss = new Date().getSeconds() < 10 ? '0' + new Date().getSeconds() : new Date().getSeconds();
      return yy + '/' + mm + '/' + dd + ' ' + hh + ':' + mf + ':' + ss;
    },
    initWebSocket() {
      this.connection();
      // let that = this;
      // // 断开重连机制,尝试发送消息,捕获异常发生时重连
      // this.timer = setInterval(() => {
      //   try {
      //     that.stompClient.send("/app/test",
      //         this.headers,
      //         JSON.stringify({'senderuid': 7, 'content': 'aaaa'}),
      //     )
      //   } catch (err) {
      //     console.log("断线了: " + err);
      //     that.connection();
      //   }
      // }, 5000);
    },
    sendMes(mes) {
      console.log("父组件发送!")
      this.stompClient.send("/app/sendTest", this.headers, JSON.stringify({
        senderuid: 7,
        content: mes,
        name: sessionStorage.getItem('nickname'),
        targetChatId: 0,
        time: this.getTime()
      }));
    },
    connection() {
      // 建立连接对象
      this.socket = new SockJS("http://localhost:8081/chatRoom//?Authorization=Bearer " + sessionStorage.getItem('token'));
      // this.socket = new SockJS("http://localhost:8081/chatRoom");
      // 获取STOMP子协议的客户端对象
      this.stompClient = Stomp.over(this.socket);
      // 定义客户端的认证信息,按需求配置
      let headers = {
        Authorization: 'Bearer ' + sessionStorage.getItem('token'),
        "Access-Control-Allow-Origin": "*"
      }
      console.log(sessionStorage.getItem('token'))
      // 向服务器发起websocket连接
      this.stompClient.connect(headers, () => {
        console.log(" 建立连接")
        this.stompClient.subscribe('/topic/0', function (response) {
          // this.stompClient.subscribe('/user/'+sessionStorage.getItem('uid'), function (response) {
          console.log(response);
          this.chat_data.push(response)
        });
      }, (err) => {
        // 连接发生错误时的处理函数
        console.log('失败')
        console.log(err);
      });
    },    //连接 后台
    disconnect() {
      if (this.stompClient) {
        this.stompClient.disconnect();
      }
    },  // 断开连接
    addTab(chatInfo) {
      if (this.tabsItem.find(item => item.chat_id === chatInfo.chat_id)) {
        console.log("already exist")
      } else {
        // console.log("not find")
        // console.log(this.tabsItem)
        this.tabIndex++;
        this.tabsItem.push({
          title: chatInfo.name,
          chat_id: chatInfo.chat_id,
          closable: false,
          ref: 'ref',
          content: ChatRoom
        });
        this.tabsPath.push({
          chat_id: chatInfo.chat_id,
          path: '/chatroom',
          path_name: 'chatroom'
        });
        // console.log(this.tabsItem)
      }
    },
    removeTab(targetName) { //删除Tab
      let tabs = this.tabsItem; //当前显示的tab数组
      let activeName = this.activeTab; //点前活跃的tab

      //如果当前tab正活跃 被删除时执行
      if (activeName === targetName) {
        tabs.forEach((tab, index) => {
          if (tab.name === targetName) {
            let nextTab = tabs[index + 1] || tabs[index - 1];
            if (nextTab) {
              activeName = nextTab.name;
              this.tabClick(nextTab)
            }
          }
        });
      }
      this.activeTab = activeName;
      this.tabsItem = tabs.filter(tab => tab.name !== targetName);
      //在tabsPath中删除当前被删除tab的path
      this.tabsPath = this.tabsPath.filter(item => item.name !== targetName)
    },
    tabClick(thisTab) {
      /*
      * thisTab:当前选中的tabs的实例
      * 通过当前选中tabs的实例获得当前实例的path 重新定位路由
      * */
      // console.log(this.$route.path)
      // let val = this.tabsPath.filter(item => thisTab.name === item.name)
      // this.$router.push({
      //   // path: val[0].path,
      //   name: val[0].path_name,
      //   query: {
      //     id:val[0].name
      //   }
      // })
      let i = this.tabsItem.find(item => item.name === thisTab.name);
      // i.content.id = thisTab.path_name;
    }
  },
  // sockets: {
  //   connect() {
  //     // this.id = this.socket.id;
  //     this.socket.emit('login', "asdfg");    //监听connect事件
  //   },
  //   message(data) {  //监听message事件，方法是后台定义和提供的
  //     console.log(data);
  //   }
  // },
  async mounted() {
    // const {data: res} = await this.$http.post(axios.defaults.baseURL + 'auth/register', {uid: sessionStorage.getItem('uid')})
    // this.$socket_path = sessionStorage.getItem('uid');
    console.log("开始初始化");
    await this.initWebSocket();
    console.log("初始化完成");
  },
  created() {
    let x = {
      name: 'aasdfg',
      chat_id: 3,
    };
    this.addTab(x);

    // //获得历史消息
    // let f={
    //   uid:sessionStorage.getItem('uid'),
    //   limit:100
    // }
    // this.$http.post(axios.defaults.baseURL + '', f).then((res) => {
    //   if(res.code==='000000'){
    //
    //   }else{
    //     this.$message.error(res.desc);
    //   }
    // })
  },
  components: {
    ChatRoom
  },
  beforeDestroy: function () {
    // 页面离开时断开连接,清除定时器
    this.disconnect();
    clearInterval(this.timer);
  }
}
</script>

<style scoped>

.el-menu-vertical-demo:not(.el-menu--collapse) {
  width: 200px;
  min-height: 400px;
  height: 100%;
}

.el-menu--collapse {
  height: 100%;
}

.el-header {
  background-color: #B3C0D1;
  color: #333;
  line-height: 60px;
}

.el-aside {
  color: #333;
}

.el-submenu [class^=fa] {
  vertical-align: middle;
  margin-right: 5px;
  width: 24px;
  text-align: center;
  font-size: 16px;
}

</style>
